var express = require('express');
var router = express.Router();
var fs = require('fs')
var path = require('path')
var MongoClient = require('mongodb').MongoClient;
var mongodb = require('mongodb')
var config = require('../config/db')    //加载数据库配置模块
var passport = require('passport') 
const jwt = require('jsonwebtoken')
// /* GET users listing. */
// //基本商品列表数据获取
// router.get('/getproductsAll', function(req, res, next) {
//   var productsid = req.query.id
//   MongoClient.connect(config.url, function (err, client) {
//     if (err) {
//       console.log('数据库连接失败', err)
//       res.json({ code: 200, message: 'error', data: err })
//     }else {
//       //3.执行条件查询操作 db.find
//       var db = client.db()
//       var flag = false
//       db.collection('products').find({ id:productsid.id }).
//       toArray(function (err, result) {
       
//         })
//     }
//       })
// })
router.get('/getAllProducts',async function(req, res, next){
  let client = await MongoClient.connect(config.url)      //获取数据库连接对象
  let db = client.db()
  let products = await db.collection('products').find({ }).toArray()    //获取所有商品数据
  console.log('products:',products)
  if (products.length > 0) {
    res.json({ code: 200, message: 'ok', data: products });   
  } else {
    res.json({ code: 200, message: 'error' });
  }
});


router.get('/getAllBooks',async function(req, res, next){
  let client = await MongoClient.connect(config.url)      //获取数据库连接对象
  let db = client.db()
  let products = await db.collection('books').find({ }).toArray()    //获取所有商品数据
  console.log('products:',products)
  if (products.length > 0) {
    res.json({ code: 200, message: 'ok', data: products });   
  } else {
    res.json({ code: 200, message: 'error' });
  }
});


router.get('/getComments',passport.authenticate('jwt',{session:false}),async function(req,res,next){
  let client = await MongoClient.connect(config.url) //获取数据库连接对象
  let db = client.db()
  let product= req.query 
  console.log('111',req.query)        
  let comments = await db.collection('comments').find({id:product.id}).toArray()
  console.log('comments:',comments)
  if(comments.length >= 0){
      res.json({code:200, message:'ok', data: comments });
  }else{
      res.json({code:200, message:'error'});
  }
});



module.exports = router;